import { defineStore } from "pinia";
import { ref } from "vue";
import type { Ref } from "vue";
import type { UserInfo, UserMessage } from "@/types/userTypes.d.ts";
import type { Code, CodeLogin, CodeParams, PasswordLogin } from "@/types/loginTypes.d.ts";
import { passwordLoginAPI, codeLoginAPI, sendCodeAPI, fetchUserMessageAPI, qqLoginAPI, bindMobilAPI } from "@/api/userApi.ts";
import { getUserInfo, removeUserInfo, setUserInfo } from "@/utils/localStorage.ts";

const useUserStore = defineStore("userStore", () => {

    /*用户信息*/
    const userInfo: Ref<UserInfo> = ref<UserInfo>(getUserInfo<UserInfo>() || <UserInfo>{});
    /*用户个人信息*/
    const userMessage: Ref<UserMessage> = ref<UserMessage>(<UserMessage>{});

    /*密码登录的请求函数*/
    const passwordLogin = async (formData: PasswordLogin): Promise<string> => {
        const { data }: { data: UserInfo } = await passwordLoginAPI(formData);
        userInfo.value = data;
        doSetUserInfo(data);
        return "密码登录成功";
    };

    /*验证码登录的请求函数*/
    const codeLogin = async (formData: CodeLogin): Promise<string> => {
        const { data }: { data: UserInfo } = await codeLoginAPI(formData);
        userInfo.value = data;
        doSetUserInfo(data);
        return "验证码登录成功";
    };

    /*qq登录的请求函数*/
    const qqLogin = async (openId: string): Promise<string> => {
        const { data }: { data: UserInfo } = await qqLoginAPI(openId);
        userInfo.value = data;
        doSetUserInfo(data);
        return "QQ登录成功";
    };

    /*绑定手机号的请求函数*/
    const bindMobil = async (formData: CodeLogin & { openId?: string }): Promise<string> => {
        const { data }: { data: UserInfo } = await bindMobilAPI(formData);
        userInfo.value = data;
        doSetUserInfo(data);
        return "手机绑定成功";
    };

    /*发送请求发送验证码的请求函数*/
    const sendCode = async (params: CodeParams): Promise<string> => {
        const { data }: { data: Code } = await sendCodeAPI(params);
        return data.code;
    };

    /*设置信息的回调函数函数*/
    const doSetUserInfo = (info: UserInfo): void => {
        setUserInfo<UserInfo>(info);
        userInfo.value = info;

    };

    /*删除信息的回调函数函数*/
    const doClearUserInfo = (): void => {
        userInfo.value = <UserInfo>{};
        removeUserInfo();
    };

    /*发送请求获取用户个人信息的请求函数*/
    const fetchUserMessage = async (): Promise<void> => {
        const { data }: { data: UserMessage } = await fetchUserMessageAPI();
        userMessage.value = data;
    };

    return {
        userInfo,
        userMessage,
        passwordLogin,
        sendCode,
        codeLogin,
        qqLogin,
        bindMobil,
        doSetUserInfo,
        doClearUserInfo,
        fetchUserMessage,
    };

});

export default useUserStore;
